package com.lvmama.rhino.service.impl.comment;

import com.lvmama.rhino.mapperComment.PredictCalcMapper;
import com.lvmama.rhino.pojo.comment.Enum.EnumForComment;
import com.lvmama.rhino.pojo.comment.entity.vo.PredictFavorRateCalcJobVO;
import com.lvmama.rhino.pojo.comment.request.PredictCalcFavorRateRequest;
import com.lvmama.rhino.service.comment.PredictCalcService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 好评率预测计算任务
 */

@Service
public class PredictCalcServiceImpl implements PredictCalcService {

    @Autowired
    private PredictCalcMapper predictCalcMapper;

    private Logger log = Logger.getLogger(PredictCalcServiceImpl.class);

    @Override
    public void deleteLastPredictData() throws Exception {
        predictCalcMapper.deleteLastPredictData();
    }

    @Override
    public List<PredictFavorRateCalcJobVO> queryPredictFavorRateData() throws Exception {
        return predictCalcMapper.queryPredictFavorRateData();
    }

    @Override
    public void savePredictFavorRateData(List<PredictFavorRateCalcJobVO> predictList) throws Exception {
        predictCalcMapper.savePredictFavorRateData(predictList);
    }

    @Override
    public void queryLastWeekFavorRate(List<PredictFavorRateCalcJobVO> predictList) {

        if (!CollectionUtils.isEmpty(predictList)) {
            for (int i = 0; i < predictList.size(); i++) {
                try {
                    PredictFavorRateCalcJobVO vo = predictList.get(i);
                    PredictCalcFavorRateRequest request = new PredictCalcFavorRateRequest();
                    request.setProductId(vo.getProductId());
                    request.setDate(vo.getLastDate());

                    // 总数
                    Long sum = predictCalcMapper.queryProDaySalesNum(request);
                    if (sum == 0) {
                        vo.setLastFavorate(0);
                        continue;
                    }

                    // 好评率总数
                    request.setSenseType(EnumForComment.positive.getValue());
                    Long favorSum = predictCalcMapper.queryProDaySalesNum(request);
                    if (favorSum == 0) {
                        vo.setLastFavorate(0);
                        continue;
                    }
                    BigDecimal favorRateBig = new BigDecimal(favorSum).divide(new BigDecimal(sum), 2, BigDecimal.ROUND_HALF_UP);
                    if (null != favorRateBig) {
                        vo.setLastFavorate(favorRateBig.floatValue());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("queryLastWeekFavorRate error:i=" + i);
                }
            }
        }
    }

}
